/*
 * @Author: 0x9DEFA478
 * @Date: 2025-06-22 16:44:25
 * @LastEditTime: 2025-09-19 21:47:30
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * 
 */
#include "HMakeDecode.hpp"
#include "HMakePath.hpp"
#include "Utility/H_Path.hpp"
#include "Utility/H_String.hpp"
#include "Tree/H_Tree_RedBlack.hpp"
#include "Container/H_Stack.hpp"
#include "SystemUtility/C_iostream.hpp"


static std::string MakeErrorString(const std::string& path,int line,int pos,const std::string& reason){
  return path+":"+std::to_string(line)+":"+std::to_string(pos)+" "+reason;
}


namespace HMake{

  
  class ValuePool{
    public:
      class SpecificValue{
        public:
          using Pointer=H::Pointer<SpecificValue>;
        public:

          SpecificValue()noexcept{}
          ~SpecificValue()noexcept{}

          SpecificValue(const SpecificValue& specificValue);

          Value::Pointer FindValue(const H::Path& path)noexcept;

          std::list<Value*> FindChildValue(const H::Path& path)noexcept;
          
          Value::Pointer AddValue(const H::Path& path)noexcept;

          std::string ToString()const;

        private:
          H::Tree::RedBlack<H::Path,Value::Pointer> values;
      };

    public:

      ValuePool()noexcept{}
      ~ValuePool()noexcept{}

      ValuePool(const ValuePool& valuePool);

      Value* FindValue(const std::string& name,const H::Path& path=H::Path::Empty)noexcept;
      const Value* FindValue(const std::string& name,const H::Path& path=H::Path::Empty)const noexcept;
      Value* FindValue(const std::string& name,const H::Path& path,const std::string& cwd)noexcept;
      const Value* FindValue(const std::string& name,const H::Path& path,const std::string& cwd)const noexcept;

      std::list<Value*> FindChildValue(const std::string& name,const H::Path& path=H::Path::Empty)noexcept;
      std::list<const Value*> FindChildValue(const std::string& name,const H::Path& path=H::Path::Empty)const noexcept;
      std::list<Value*> FindChildValue(const std::string& name,const H::Path& path,const std::string& cwd)noexcept;
      std::list<const Value*> FindChildValue(const std::string& name,const H::Path& path,const std::string& cwd)const noexcept;

      Value::Pointer AddValue(const std::string& name,const H::Path& path=H::Path::Empty)noexcept;
      Value::Pointer AddValue(const std::string& name,const H::Path& path,const std::string& cwd)noexcept;

      std::string ToString()const;

    private:
      H::Tree::RedBlack<std::string,SpecificValue::Pointer> values;

  };
  

  ValuePool::SpecificValue::SpecificValue(const SpecificValue& specificValue){
    for(auto& Item:specificValue.values){
// #if __cplusplus >= 202000L
//       values.try_emplace(Item.first,Value::Pointer(new Value(*Item.second)));
// #else
//       values.emplace(Item.first,Value::Pointer(new Value(*Item.second)));
// #endif
      values.Insert(Item.Key(),Value::Pointer(new Value(*Item.Data())));
    }
  }

  Value::Pointer ValuePool::SpecificValue::FindValue(const H::Path& path)noexcept{
    auto res=values.Find(path);
    if(res!=values.end()){
      return res->Data();
    }
    return Value::New();
  }
  
  std::list<Value*> ValuePool::SpecificValue::FindChildValue(const H::Path& path)noexcept{
    std::list<Value*> r;
    auto res=values.rbegin();
    //依赖于map是升序的
    while(res!=values.rend()){
      if(res->Key().IsParentOrEqual(path)){
        r.emplace_back(res->Data());
      }
      res++;
    }
    return r;
  }

  Value::Pointer ValuePool::SpecificValue::AddValue(const H::Path& path)noexcept{
// #if __cplusplus >= 202000L
//     auto res=values.try_emplace(path);
//     if(res.second){
//       res.first->second=Value::Pointer(new Value);
//     }
// #else
//     auto res=values.emplace(path,Value::Pointer(new Value));
// #endif
//     return res.first->second;

    return values.Insert(path,Value::Pointer(new Value)).iterator->Data();
  }
  
  std::string ValuePool::SpecificValue::ToString()const{
    std::stringstream ss;
    for(auto& Item:values){
      ss<<"{"<<Item.Key().String()<<","<<Item.Data()->String()<<"} ";
    }
    return ss.str();
  }


  ValuePool::ValuePool(const ValuePool& valuePool){
    for(auto& Item:valuePool.values){
// #if __cplusplus >= 202000L
//       values.try_emplace(Item.first,SpecificValue::Pointer(new SpecificValue(*Item.second)));
// #else
//       values.emplace(Item.first,SpecificValue::Pointer(new SpecificValue(*Item.second)));
// #endif
      values.Insert(Item.Key(),SpecificValue::Pointer(new SpecificValue(*Item.Data())));
    }
  }

  static H::Path ToFullPath(const H::Path& path,const std::string& cwd){
    H::Path fullPath;

    if(path.IsRelative()){
      fullPath=H::Path(cwd)+path;
    }else{
      fullPath=path;
    }

    return fullPath;
  }

  Value* ValuePool::FindValue(const std::string& name,const H::Path& path)noexcept{
    // auto res=values.find(name);
    // if(res!=values.end()){
    //   return res->second->FindValue(path.DiscardRelative());
    // }
    // return nullptr;
    auto res=values.Find(name);
    if(res!=values.end()){
      return res->Data()->FindValue(path.DiscardRelative());
    }
    return nullptr;
  }

  const Value* ValuePool::FindValue(const std::string& name,const H::Path& path)const noexcept{
    auto res=values.Find(name);
    if(res!=values.end()){
      return res->Data()->FindValue(path.DiscardRelative());
    }
    return nullptr;
  }

  Value* ValuePool::FindValue(const std::string& name,const H::Path& path,const std::string& cwd)noexcept{
    return FindValue(name,ToFullPath(path,cwd));
  }

  const Value* ValuePool::FindValue(const std::string& name,const H::Path& path,const std::string& cwd)const noexcept{
    return FindValue(name,ToFullPath(path,cwd));
  }

  std::list<Value*> ValuePool::FindChildValue(const std::string& name,const H::Path& path)noexcept{
    auto res=values.Find(name);
    if(res!=values.end()){
      return res->Data()->FindChildValue(path.DiscardRelative());
    }
    return {};
  }

  std::list<const Value*> ValuePool::FindChildValue(const std::string& name,const H::Path& path)const noexcept{
    auto res=values.Find(name);
    if(res!=values.end()){
      std::list<const Value*> r;
      for(auto& Item:res->Data()->FindChildValue(path.DiscardRelative())){
        r.emplace_back(Item);
      }
      return r;
    }
    return {};
  }

  std::list<Value*> ValuePool::FindChildValue(const std::string& name,const H::Path& path,const std::string& cwd)noexcept{
    return FindChildValue(name,ToFullPath(path,cwd));
  }

  std::list<const Value*> ValuePool::FindChildValue(const std::string& name,const H::Path& path,const std::string& cwd)const noexcept{
    return FindChildValue(name,ToFullPath(path,cwd));
  }

  Value::Pointer ValuePool::AddValue(const std::string& name,const H::Path& path)noexcept{
// #if __cplusplus >= 202000L
//     auto res=values.try_emplace(name,SpecificValue::Pointer(new SpecificValue));
// #else
//     auto res=values.emplace(name,SpecificValue::Pointer(new SpecificValue));
// #endif
//     return res.first->second->AddValue(path.DiscardRelative());
    return values.Insert(name,SpecificValue::Pointer(new SpecificValue)).iterator->Data()->AddValue(path.DiscardRelative());
  }

  Value::Pointer ValuePool::AddValue(const std::string& name,const H::Path& path,const std::string& cwd)noexcept{
// #if __cplusplus >= 202000L
//     auto res=values.try_emplace(name,SpecificValue::Pointer(new SpecificValue));
// #else
//     auto res=values.emplace(name,SpecificValue::Pointer(new SpecificValue));
// #endif
//     return res.first->second->AddValue(ToFullPath(path,cwd).DiscardRelative());
    return values.Insert(name,SpecificValue::Pointer(new SpecificValue)).iterator->Data()->AddValue(ToFullPath(path,cwd).DiscardRelative());
  }

  std::string ValuePool::ToString()const{
    std::stringstream ss;

    for(auto& Item:values){
      ss<<"name: "<<Item.Key()<<" value:"<<Item.Data()->ToString()<<std::endl;
    }
    return ss.str();
  }


  
  
  class TargetConfig_HMK:public TargetConfig{
    public:
      template<typename... T_Arg>
      static Pointer New(T_Arg&&... Args){
        return Pointer(new TargetConfig_HMK(std::forward<T_Arg>(Args)...));
      }

    public:
      TargetConfig_HMK(const std::string& name,const ValuePool& valuePool);

      virtual const Value* FindValue(const std::string& valueName,const H::Path& path)const;
      virtual const Value* FindValue(const std::string& valueName,const H::Path& path,const std::string& cwd)const;
      virtual std::list<const Value*> FindChildValue(const std::string& valueName,const H::Path& path)const;
      virtual std::list<const Value*> FindChildValue(const std::string& valueName,const H::Path& path,const std::string& cwd)const;

      virtual std::string ToString()const;

    private:
      const ValuePool valuePool;
  };

  TargetConfig_HMK::TargetConfig_HMK(const std::string& name,const ValuePool& valuePool):TargetConfig(name),valuePool(valuePool){
  }

  const Value* TargetConfig_HMK::FindValue(const std::string& valueName,const H::Path& path)const{
    return valuePool.FindValue(valueName,path);
  }
  
  const Value* TargetConfig_HMK::FindValue(const std::string& valueName,const H::Path& path,const std::string& cwd)const{
    return valuePool.FindValue(valueName,path,cwd);
  }

  std::list<const Value*> TargetConfig_HMK::FindChildValue(const std::string& valueName,const H::Path& path)const{
    return valuePool.FindChildValue(valueName,path);
  }

  std::list<const Value*> TargetConfig_HMK::FindChildValue(const std::string& valueName,const H::Path& path,const std::string& cwd)const{
    return valuePool.FindChildValue(valueName,path,cwd);
  }

  std::string TargetConfig_HMK::ToString()const{
    std::stringstream ss;
    std::stringstream lines;
    ss<<"config_name:"<<Name()<<std::endl;
    lines<<valuePool.ToString();

    while(!lines.eof()){
      std::string lineStr;
      std::getline(lines,lineStr);
      ss<<"  "<<lineStr<<std::endl;
    }

    return ss.str();
  }




  Decoder::Decoder(const std::string& cwd,const std::string& targetName)noexcept:cwd(cwd),targetName(targetName){
    valuePool=nullptr;

    ResetValuePool();

    auto bind_arg=[this](auto func){
      return std::bind(func,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3,std::placeholders::_4);
    };

    functionMap["if"]=bind_arg(&Decoder::Function_if);
    functionMap["eq"]=bind_arg(&Decoder::Function_eq);
    functionMap["ne"]=bind_arg(&Decoder::Function_ne);
    functionMap["not"]=bind_arg(&Decoder::Function_not);
    functionMap["and"]=bind_arg(&Decoder::Function_and);
    functionMap["or"]=bind_arg(&Decoder::Function_or);
    functionMap["IsSuffix"]=bind_arg(&Decoder::Function_IsSuffix);
    functionMap["GetLine"]=bind_arg(&Decoder::Function_GetLine);
    functionMap["PopLine"]=bind_arg(&Decoder::Function_PopLine);
    functionMap["ArrayToString"]=bind_arg(&Decoder::Function_ArrayToString);
    functionMap["ClearContext"]=bind_arg(&Decoder::Function_ClearContext);
    functionMap["SetTargetConfig"]=bind_arg(&Decoder::Function_SetTargetConfig);
    functionMap["DirectoryRecursive"]=bind_arg(&Decoder::Function_DirectoryRecursive);
    functionMap["FileFromDirectory"]=bind_arg(&Decoder::Function_FileFromDirectory);
    functionMap["FileFromDirectoryRecursive"]=bind_arg(&Decoder::Function_FileFromDirectoryRecursive);
    functionMap["Print"]=bind_arg(&Decoder::Function_Print);
    
  }

  Decoder::~Decoder(){
    if(valuePool!=nullptr){
      delete valuePool;
    }
  }

  void Decoder::Load(const std::string& path){

    auto ea=Expression::decode(path,HMK_Element::decode(path));

    for(auto& Item:ea){
      ExecuteLine(Item,path);
    }

  }

  


  void Decoder::ExecuteLine(const HMake::Expression::Pointer& LinePointer,const std::string& path){
    struct DecodeResult{
      enum class Type:int{
        Text=0,
        Value=1,
        ValueArray=2,
        Operator=3,
      };

      Type type;
      bool isInBrackets;//用于逗号运算符的处理判断 标记是否在括号内
      Expression::Pointer text;
      Value::Pointer value;
      std::vector<Value::Pointer> valueArray;
      std::string Operator;

      int line;
      int pos;

      DecodeResult(int line,int pos):isInBrackets(false),line(line),pos(pos){}
    };
    struct StackItem{

      int line;
      int pos;

      std::vector<Expression::Pointer> expressionArray;
      std::vector<DecodeResult> resultArray;

      StackItem(const Expression_Collection* Collection):line(Collection->line()),pos(Collection->pos()),expressionArray(Collection->Colloection()){}
    };

    if(LinePointer->type()!=Expression::Type::Collection){
      return;
    }

    H::Stack<StackItem> stack;
    StackItem currentStatus(LinePointer->ToType<Expression_Collection>());

    if(currentStatus.expressionArray.size()==0){
      return;
    }

    for(;;){

      for(;;){
        auto Length=currentStatus.expressionArray.size();
        auto Index=currentStatus.resultArray.size();

        //求子表达式的值
        while(Index<Length){

          if(currentStatus.expressionArray[Index]->type()==Expression::Type::Collection){
            break;
          }

          DecodeResult res(currentStatus.expressionArray[Index]->line(),currentStatus.expressionArray[Index]->pos());

          res.type=DecodeResult::Type::Text;
          res.text=currentStatus.expressionArray[Index];
          currentStatus.resultArray.emplace_back(res);
          Index++;
        }
        if(Index<Length){//有子表达式需要迭代求值
          stack.Push(currentStatus);
          currentStatus=StackItem(currentStatus.expressionArray[Index]->ToType<Expression_Collection>());
          continue;
        }

        //只有一个元素 使用简化的求解方式
        if(Length==1){
          if(!stack.Empty()){
            auto res=currentStatus.resultArray[0];

            if(currentStatus.expressionArray[0]->type()==Expression::Type::Collection){
              if(currentStatus.expressionArray[0]->ToType<Expression_Collection>()->BeginChar()!=' '){
                res.isInBrackets=true;
              }
            }

            stack.Top().resultArray.emplace_back(res);
          }
          break;
        }

        //解析表达式

        std::vector<DecodeResult> expr;
        
        auto addText=[&expr](DecodeResult& item,bool isInBrackets){
          auto val=Value::New();
          *val=item.text->ToType<Expression_Text>()->Text();

          DecodeResult res(item.text->line(),item.text->pos());
          res.type=DecodeResult::Type::Value;
          res.isInBrackets=isInBrackets;
          res.value=val;

          expr.emplace_back(res);
        };

        auto executeFunc=[this,path,&expr](DecodeResult& item,bool isInBrackets,const std::vector<Value::Pointer>& args){
          DecodeResult res(item.text->line(),item.text->pos());
          res.type=DecodeResult::Type::Value;
          res.isInBrackets=true;
          res.value=ExecuteFunction(item.text->ToType<Expression_Text>()->Text(),args,item.text->line(),item.text->pos(),path);

          expr.emplace_back(res);
        };

        auto expressionIsInBrackets=[](const Expression::Pointer& expression){
          bool isInBrackets=false;
          if(expression->type()==Expression::Type::Collection){
            if(expression->ToType<Expression_Collection>()->BeginChar()!=' '){
              isInBrackets=true;
            }
          }
          return isInBrackets;
        };

        Index=0;
        while(Index<Length){

          auto& item=currentStatus.resultArray[Index];
          bool isInBrackets=expressionIsInBrackets(currentStatus.expressionArray[Index]);

          if(item.type==DecodeResult::Type::Text){
            //将未解析的表达式解析 解析变量 解析函数并执行


            switch(item.text->type()){
              case Expression::Type::ValueMark:

                Index++;
                if(Index>=Length){
                  throw std::runtime_error(MakeErrorString(path,item.text->line(),item.text->pos(),"'$' 没有有效的变量名"));
                }

                {
                  auto& valuename=currentStatus.resultArray[Index];
                  bool valueIsInBrackets=expressionIsInBrackets(currentStatus.expressionArray[Index]);

                  switch(valuename.type){
                    case DecodeResult::Type::Text:
                      {
                        if(!(valueIsInBrackets||valuename.isInBrackets)){
                          throw std::runtime_error(MakeErrorString(path,item.text->line(),item.text->pos(),"'$'之后的变量名没有使用括号包裹"));
                        }
                        DecodeResult res(valuename.line,valuename.pos);
                        switch(valuename.text->type()){
                          case Expression::Type::Text:
                            res.value=valuePool->AddValue(valuename.text->ToType<Expression_Text>()->Text());
                            break;
                          case Expression::Type::String:
                            res.value=valuePool->AddValue(valuename.text->ToType<Expression_String>()->str());
                            break;
                          default:
                            throw std::runtime_error(MakeErrorString(path,valuename.text->line(),valuename.text->pos(),"该表达式不能做变量名"));
                        }

                        res.type=DecodeResult::Type::Value;
                        res.isInBrackets=true;

                        expr.emplace_back(res);
                      }
                      break;
                    case DecodeResult::Type::Value:
                      {
                        H::Path val_path;
                        auto& ValueArray=valuename.value->ValueArray();

                        if(ValueArray.Length()<1){
                          throw std::runtime_error(MakeErrorString(path,valuename.text->line(),valuename.text->pos(),"该表达式不能做变量名"));
                        }
                        if(ValueArray.Length()>1){
                          val_path=H::Path(ValueArray[1]);
                        }

                        DecodeResult res(valuename.line,valuename.pos);
                        res.type=DecodeResult::Type::Value;
                        res.isInBrackets=true;
                        res.value=valuePool->AddValue(ValueArray[0],val_path,cwd);

                        expr.emplace_back(res);
                      }
                      break;
                    default:
                      throw std::runtime_error(MakeErrorString(path,valuename.line,valuename.pos,"该表达式不能做变量名"));
                  }
                }
                break;

              case Expression::Type::Text:
                if((Index+1)>=Length){//尾部的text转为变量
                  addText(item,isInBrackets);
                }else{
                  Index++;

                  auto& argList=currentStatus.resultArray[Index];
                  bool argListIsInBrackets=expressionIsInBrackets(currentStatus.expressionArray[Index]);

                  switch(argList.type){
                    case DecodeResult::Type::Text:
                      if(argList.text->IsOper()){//操作符可以将text转为变量
                        addText(item,isInBrackets);
                        Index--;
                        break;
                      }

                      if(!(argListIsInBrackets||argList.isInBrackets)){
                        throw std::runtime_error(MakeErrorString(path,item.text->line(),item.text->pos(),"函数没有参数列表(Text)"));
                      }

                      {
                        auto value=Value::New();
                        
                        switch(argList.text->type()){
                          case Expression::Type::String:
                            *value=argList.text->ToType<Expression_String>()->str();
                            break;
                          case Expression::Type::Text:
                            *value=argList.text->ToType<Expression_Text>()->Text();
                            break;
                          default:
                            throw std::runtime_error(MakeErrorString(path,argList.text->line(),argList.text->pos(),"不能作为函数参数"));
                        }

                        executeFunc(item,true,{value});
                      }
                      break;
                    case DecodeResult::Type::Value:
                      if(!(argListIsInBrackets||argList.isInBrackets)){
                        throw std::runtime_error(MakeErrorString(path,item.text->line(),item.text->pos(),"函数没有参数列表(Value)"));
                      }
                      
                      executeFunc(item,true,{argList.value});
                      break;
                    case DecodeResult::Type::ValueArray:
                      if(!(argListIsInBrackets||argList.isInBrackets)){
                        throw std::runtime_error(MakeErrorString(path,item.text->line(),item.text->pos(),"函数没有参数列表(ValueArray)"));
                      }
                      
                      executeFunc(item,true,argList.valueArray);
                      break;
                    default:
                      //默认保持原样
                      addText(item,argListIsInBrackets);
                      Index--;
                      break;
                  }

                }
                break;
              case Expression::Type::String:
                {
                  auto val=Value::New();
                  *val=item.text->ToType<Expression_String>()->str();

                  DecodeResult res(item.text->line(),item.text->pos());
                  res.type=DecodeResult::Type::Value;
                  res.value=val;

                  expr.emplace_back(res);
                }
                break;
              case Expression::Type::Assignment:
                {
                  DecodeResult res(item.text->line(),item.text->pos());
                  res.type=DecodeResult::Type::Operator;

                  res.Operator=item.text->ToType<Expression_Operator>()->Operator();
                  if(item.text->ToType<Expression_Operator>()->Operator()!='='){
                    res.Operator+="=";
                  }

                  expr.emplace_back(res);
                }
                break;
              case Expression::Type::Arithmetic:
                {
                  DecodeResult res(item.text->line(),item.text->pos());
                  res.type=DecodeResult::Type::Operator;

                  res.Operator=item.text->ToType<Expression_Operator>()->Operator();

                  expr.emplace_back(res);
                }
                break;
              default:
                throw std::runtime_error(MakeErrorString(path,item.text->line(),item.text->pos(),"不识别的表达式"));
            }

          }else{
            auto new_item=item;
            if(isInBrackets){
              new_item.isInBrackets=true;
            }
            expr.emplace_back(new_item);//已解析的表达式 保持原样
          }
          Index++;
        }

        //表达式求值

        if(expr.size()<1){
          if(!stack.Empty()){
            DecodeResult res(currentStatus.line,currentStatus.pos);
            res.type=DecodeResult::Type::ValueArray;
            stack.Top().resultArray.emplace_back(res);
          }
          break;
        }

        if(expr.size()==1){
          if(!stack.Empty()){
            stack.Top().resultArray.emplace_back(expr[0]);
          }
          break;
        }

        //至少两个元素
        bool valueValid=false;
        bool valueIsArray=false;
        Value::Pointer value;
        std::vector<Value::Pointer> valArray;
        std::string operatorStr="";

        for(std::size_t i=0,length=expr.size();i<length;i++){
          auto& exprItem=expr[i];

          switch(exprItem.type){
            case DecodeResult::Type::Value:
              if(valueValid){
                if(operatorStr.length()<1){
                  throw std::runtime_error(MakeErrorString(path,exprItem.line,exprItem.pos,"变量与变量之间没有运算符"));
                }

                if(valueIsArray){
                  if(operatorStr!=","){
                    throw std::runtime_error(MakeErrorString(path,exprItem.line,exprItem.pos,"变量组无法与变量进行非','运算"));
                  }
                  valArray.emplace_back(exprItem.value);
                }else{
                  try{
                    if(operatorStr=="="){
                      *value=*exprItem.value;
                    }else if(operatorStr=="+="){
                      *value+=*exprItem.value;
                    }else if(operatorStr=="+"){
                      value=Value::New(*value+*exprItem.value);
                    }else if(operatorStr=="-"){
                      value=Value::New(*value-*exprItem.value);
                    }else if(operatorStr=="-="){
                      *value-=*exprItem.value;
                    }else if(operatorStr==":"){
                      value=Value::New(value->ToArray()+*exprItem.value);
                    }else if(operatorStr==","){
                      valueIsArray=true;
                      valArray.emplace_back(value);
                      valArray.emplace_back(exprItem.value);
                    }else{
                      throw std::runtime_error("不支持'"+operatorStr+"'运算符");
                    }
                  }catch(const std::runtime_error& e){
                    throw std::runtime_error(MakeErrorString(path,exprItem.line,exprItem.pos,e.what()));
                  }
                }
              }else{//没有有效的值
                valueValid=true;
                value=exprItem.value;
                if(operatorStr==":"){//数组变量
                  value=Value::New(value->ToArray());
                }
              }
              operatorStr="";
              break;
            case DecodeResult::Type::ValueArray:
              if(valueValid){
                if(operatorStr!=","){
                  throw std::runtime_error(MakeErrorString(path,exprItem.line,exprItem.pos,"变量组无法进行非','运算"));
                }
                if(!valueIsArray){
                  valueIsArray=true;
                  valArray.emplace_back(value);
                }
                for(auto& item:exprItem.valueArray){
                  valArray.emplace_back(item);
                }
              }else{
                valueValid=true;
                valueIsArray=true;
                valArray=exprItem.valueArray;
              }
              operatorStr="";
              break;
            case DecodeResult::Type::Operator:
              //如果是单目后置运算符, 则需要在这里计算
              
              operatorStr=exprItem.Operator;

              if((i+1)>=length){
                //运算符在尾部
                try{
                  if(exprItem.Operator=="="){
                    *value=Value();
                    operatorStr="";
                  }else if(exprItem.Operator==":"){
                    if(!value->IsArray()){
                      auto array=value->ToArray();
                      *value=Value();
                      *value=array;
                    }
                  }
                }catch(const std::runtime_error& e){
                  throw std::runtime_error(MakeErrorString(path,exprItem.line,exprItem.pos,e.what()));
                }
              }

              break;
            default:
              throw std::logic_error(MakeErrorString(path,exprItem.line,exprItem.pos,"内部逻辑错误 该类型的表达式结果不应出现在这里"));
          }

        }

        if(!stack.Empty()){
          DecodeResult res(currentStatus.line,currentStatus.pos);

          if((!valueValid)||valueIsArray){
            res.type=DecodeResult::Type::ValueArray;
            res.valueArray=valArray;
          }else{
            res.type=DecodeResult::Type::Value;
            res.value=value;
          }
          stack.Top().resultArray.emplace_back(res);
        }

        break;
      }

      if(stack.Empty()){
        break;
      }
      currentStatus=stack.Top();
      stack.Pop();
    }

  }




  Value::Pointer Decoder::ExecuteFunction(const std::string& functionName,const Args_t& args,int line,int pos,const std::string& path){
    const std::string* FunctionName;
    const Args_t* Args;
    std::string functionName_loc;
    Args_t args_loc;

    const std::string suffix=".if";
    if(H::String::IsSuffix(functionName,suffix)){
      auto argCount=args.size();

      if(argCount<1){
        throw std::runtime_error(MakeErrorString(path,line,pos,"带\".if\"的函数的参数列表开头需要1个参数, 作为判断"));
      }

      if(!Value::bool_Value(args[0])){
        return Value::New();
      }

      functionName_loc=std::string(functionName,0,functionName.length()-suffix.length());
      for(std::size_t i=1;i<argCount;i++){
        args_loc.emplace_back(args[i]);
      }

      FunctionName=&functionName_loc;
      Args=&args_loc;
    }else{
      FunctionName=&functionName;
      Args=&args;
    }

    auto res=functionMap.Find(*FunctionName);
    if(res==functionMap.end()){
      throw std::runtime_error(MakeErrorString(path,line,pos,"不支持的函数\""+functionName+"\""));
    }

    return res->Data()(*Args,line,pos,path);
  }


  void Decoder::ResetValuePool(){
    if(valuePool!=nullptr){
      delete valuePool;
    }
    valuePool=new ValuePool;

    valuePool->AddValue("null")->SetConst(true);

    {
      auto inputTargetName=valuePool->AddValue("HMake.Input.TargetName");

      *inputTargetName=targetName;
      inputTargetName->SetConst(true);
    }

    {
      auto cwdValue=valuePool->AddValue("HMake.CurrentWorkingDirectory");
  
      *cwdValue=cwd;
      cwdValue->SetConst(true);
    }

    {
      auto cwdPath=H::Path(cwd);
      auto cwdName=valuePool->AddValue("HMake.CurrentWorkingDirectoryName");
      auto cwdNameStr=cwdPath.Name();

      if(cwdNameStr.length()<1){
        throw std::runtime_error("cwd执行的目录名不能为空, 这可能是cwd为根目录所引起的");
      }

      *cwdName=cwdNameStr;
      cwdName->SetConst(true);
    }
  }


  Value::Pointer Decoder::Function_if(const Args_t& args,int line,int pos,const std::string& path){

    if(args.size()<2){
      throw std::runtime_error(MakeErrorString(path,line,pos,"if函数至少需要两个参数"));
    }

    if(Value::bool_Value(args[0])){
      return args[1];//返回引用
    }

    if(args.size()>2){
      return args[2];//返回引用
    }

    return Value::New();
  }

  Value::Pointer Decoder::Function_eq(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()!=2){
      throw std::runtime_error(MakeErrorString(path,line,pos,"eq函数需要两个参数"));
    }

    if(*args[0]==*args[1]){
      *r="true";
    }
    return r;
  }
  
  Value::Pointer Decoder::Function_ne(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()!=2){
      throw std::runtime_error(MakeErrorString(path,line,pos,"ne函数需要两个参数"));
    }

    if(*args[0]!=*args[1]){
      *r="true";
    }
    return r;
  }

  Value::Pointer Decoder::Function_not(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()!=1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"ne函数需要一个参数"));
    }

    if(!Value::bool_Value(args[0])){
      *r="true";
    }
    return r;
  }
  
  Value::Pointer Decoder::Function_and(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"and函数需要至少一个参数"));
    }

    for(auto& Item:args){
      if(!Value::bool_Value(Item)){
        return r;
      }
    }
    *r="true";
    return r;
  }

  Value::Pointer Decoder::Function_or(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"or函数需要至少一个参数"));
    }

    for(auto& Item:args){
      if(Value::bool_Value(Item)){
        *r="true";
        return r;
      }
    }
    return r;
  }

  Value::Pointer Decoder::Function_IsSuffix(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()!=2){
      throw std::runtime_error(MakeErrorString(path,line,pos,"IsSuffix函数需要两个参数"));
    }

    for(auto& Item:args){
      if(!Item->IsSingle()){
        throw std::runtime_error(MakeErrorString(path,line,pos,"IsSuffix的参数类型必须为\"单个值\""));
      }
    }

    if(H::String::IsSuffix(args[0]->ValueArray()[0],args[1]->ValueArray()[0])){
      *r="true";
    }
    return r;
  }

  Value::Pointer Decoder::Function_GetLine(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"GetLine函数需要至少一个参数"));
    }

    if(args[0]->IsNone()){
      *r="";
      return r;
    }

    if(!args[0]->IsSingle()){
      throw std::runtime_error(MakeErrorString(path,line,pos,"GetLine的第一个参数必须为字符串或者空"));
    }

    char splitChar='\n';

    if((args.size()>1)&&(args[1].Length()>0)&&(args[1]->ValueArray().Length()>0)&&(args[1]->ValueArray()[0].length()>0)){
      splitChar=args[1]->ValueArray()[0][0];
    }

    std::stringstream ss(args[0]->ValueArray()[0]);
    std::string s;

    if(!ss.eof()){
      std::getline(ss,s,splitChar);
    }

    *r=s;
    return r;
  }

  Value::Pointer Decoder::Function_PopLine(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"PopLine函数需要至少一个参数"));
    }

    if(args[0]->IsNone()){
      *r="";
      return r;
    }

    if(!args[0]->IsSingle()){
      throw std::runtime_error(MakeErrorString(path,line,pos,"PopLine的第一个参数必须为字符串或者空"));
    }

    char splitChar='\n';

    if((args.size()>1)&&(args[1].Length()>0)&&(args[1]->ValueArray().Length()>0)&&(args[1]->ValueArray()[0].length()>0)){
      splitChar=args[1]->ValueArray()[0][0];
    }

    const std::string& s=args[0]->ValueArray()[0];

    auto length=s.length();
    for(std::size_t i=0;i<length;i++){
      if(s[i]==splitChar){
        if(i<(length-1)){
          *r=std::string(s,i+1);
        }
        return r;
      }
    }

    return r;
  }

  Value::Pointer Decoder::Function_ArrayToString(const Args_t& args,int line,int pos,const std::string& path){
    auto r=Value::Pointer::New();
    if(args.size()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"ArrayToString函数需要至少一个参数"));
    }

    if(args[0]->IsNone()){
      *r="";
      return r;
    }

    std::string insertStr=" ";

    if((args.size()>1)&&(args[1].Length()>0)&&(args[1]->ValueArray().Length()>0)){
      insertStr=args[1]->ValueArray()[0];
    }

    std::stringstream ss;
    for(std::size_t i=0,length=args[0]->ValueArray().Length();i<length;i++){
      if(i>0){
        ss<<insertStr;
      }
      ss<<args[0]->ValueArray()[i];
    }

    *r=ss.str();

    return r;
  }

  Value::Pointer Decoder::Function_ClearContext(const Args_t& args,int line,int pos,const std::string& path){
    
    ResetValuePool();

    return Value::New();
  }

  Value::Pointer Decoder::Function_SetTargetConfig(const Args_t& args,int line,int pos,const std::string& path){

    if(args.size()!=1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"该函数参数必须为1"));
    }

    if(args[0]->IsArray()){
      throw std::runtime_error(MakeErrorString(path,line,pos,"该函数参数不能为数组"));
    }

    auto val=args[0]->ValueArray();

    if(val.Length()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"该函数参数不能为空"));
    }

    auto& name=val[0];

    auto res=TargetConfigCollection.Insert(name,TargetConfig_HMK::New(name,*valuePool));
    if(!res.ok){
      throw std::runtime_error(MakeErrorString(path,line,pos,"重复的目标"));
    }

    return Value::New();
  }

  Value::Pointer Decoder::Function_DirectoryRecursive(const Args_t& args,int line,int pos,const std::string& path){
    Value::Pointer r=Value::New();

    if(args.size()!=1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"该函数需要一个参数"));
    }

    H::Path cwd;

    {
      auto cwdval=valuePool->FindValue("HMake.CurrentWorkingDirectory");
      if(cwdval->Valid()){
        cwd=H::Path(cwdval->ValueArray()[0]);
      }
    }

    auto valueArray=args[0]->ValueArray();
    for(H::usize i=0,length=valueArray.Length();i<length;i++){
      auto path=H::Path(valueArray[i]);
      H::Path basePath;
      std::list<PathItem> paths;

      if(path.IsRelative()){
        basePath=cwd+path;
      }else{
        basePath=path;
      }

      EnumFileDirectoryRecursive(paths,basePath);
      for(auto& Item:paths){
        if(!Item.IsDirectory){
          continue;
        }
        
        Value val;

        val=(path+Item.path).String();

        if(r->Valid()){
          *r+=val;
        }else{
          r=Value::New();
          *r=val.ToArray();
        }
      }
    }
    
    return r;
  }

  Value::Pointer Decoder::FileFromDirectory(const Args_t& args,int line,int pos,const std::string& path,bool IsRecursive){
    Value::Pointer r=Value::New();

    if(args.size()<1){
      throw std::runtime_error(MakeErrorString(path,line,pos,"该函数需要至少一个参数"));
    }

    std::vector<std::string> suffixArray;
    if(args.size()>1){
      if(args[1]->Valid()){
        auto valueArray=args[1]->ValueArray();

        for(H::usize i=0,length=valueArray.Length();i<length;i++){
          suffixArray.emplace_back(valueArray[i]);
        }
      }
    }

    H::Path cwd;

    {
      auto cwdval=valuePool->FindValue("HMake.CurrentWorkingDirectory");
      if(cwdval->Valid()){
        cwd=H::Path(cwdval->ValueArray()[0]);
      }
    }

    auto valueArray=args[0]->ValueArray();
    for(H::usize i=0,length=valueArray.Length();i<length;i++){
      auto path=H::Path(valueArray[i]);
      H::Path basePath;
      std::list<PathItem> paths;

      if(path.IsRelative()){
        basePath=cwd+path;
      }else{
        basePath=path;
      }

      if(IsRecursive){
        EnumFileDirectoryRecursive(paths,basePath);
      }else{
        EnumFileDirectory(paths,basePath);
      }

      for(auto& Item:paths){
        if(Item.IsDirectory){
          continue;
        }
        if(!suffixArray.empty()){
          bool IsFind=false;
          for(auto& suffix:suffixArray){
            if(Item.path.IsSuffix(suffix)){
              IsFind=true;
              break;
            }
          }
          if(!IsFind){
            continue;
          }
        }

        Value val;

        val=(path+Item.path).String();

        if(r->Valid()){
          *r+=val;
        }else{
          r=Value::New();
          *r=val.ToArray();
        }
      }
    }

    return r;
  }

  Value::Pointer Decoder::Function_FileFromDirectory(const Args_t& args,int line,int pos,const std::string& path){
    return FileFromDirectory(args,line,pos,path,false);
  }
  
  Value::Pointer Decoder::Function_FileFromDirectoryRecursive(const Args_t& args,int line,int pos,const std::string& path){
    return FileFromDirectory(args,line,pos,path,true);
  }
  
  Value::Pointer Decoder::Function_Print(const Args_t& args,int line,int pos,const std::string& path){
    H::cout<<path<<":"<<line<<":"<<pos<<":";

    bool IsOut=false;
    for(auto& Item:args){
      if(Item->Valid()){
        auto value=Item->ValueArray();

        for(H::usize i=0,length=value.Length();i<length;i++){
          if(i>0){
            H::cout<<":";
          }
          H::cout<<"\""<<value[i]<<"\"";
        }
        if(!IsOut){
          H::cout<<",";
          IsOut=true;
        }
      }
    }
    H::cout<<std::endl;

    return Value::New();
  }


}

